import axios from 'axios'; // 引入axios
import router from "@/router/router";
import {ElMessage} from "element-plus";
const service = axios.create({
    baseURL: 'http://localhost:8080',
    // url = base url + request url
    // withCredentials: true,
    // send cookies when cross-domain requests
    timeout: 5000, // request timeout
    headers: {'Content-Type': 'application/json;charset=UTF-8'}
})

service.interceptors.request.use(
    config => {
        const token = sessionStorage.getItem('token');
        if (token) {
            config.headers.authorization = token
        }
        // 全局请求配置
        return config;
    },
    error => {
        // do something with request error
        console.log(error) // for debug
        return Promise.reject(error)
    }
)

service.interceptors.response.use(async response => {
    //业务逻辑异常在此处修改
    if (response.data.code !== 200) {
        ElMessage({
            message: response.data.msg,
            type: 'error',
        })
        if (response.data.code === 3017) {
            sessionStorage.removeItem('token');
            await router.push('/login')
        }
    }
    // 相应数据处理器
    return response;
}, error => {
    // 对响应错误做点什么
    return Promise.reject(error);
});

export default service;